var canvasContext;
Component({
    properties: {
        width: {
            type: Number | Boolean,
            value: false
        },
        height: {
            type: Number | Boolean,
            value: false
        },
        penColor: {
            type: String,
            value: '#333333'
        },
        penWidth: {
            type: Number,
            value: 5
        },
        textAlign: {
            type: String,
            value: 'center'
        },
        textBaseline: {
            type: String,
            value: 'top'
        },
        textFont: {
            type: String,
            value: '20px fangsong'
        },
        textObj: {
            type: Object,
            value: {
                content: '请灰色区域内完成签名',
            }
        },
        saveToAlbum: {
            type: Boolean,
            value: false
        }
    },
    lifetimes: {
        attached: function () {
            this.init()
        },
    },
    data: {
        isDrawing: false,
        lastX: 0,
        lastY: 0,
    },
    methods: {
        init() {
            let {width, height} = this.data;
            if (width === false || height === false) {
                const systemInfo = wx.getSystemInfoSync();
                this.setData({
                    width: width === false ? systemInfo.windowWidth * systemInfo.pixelRatio : width,
                    height: height === false ? systemInfo.windowHeight * systemInfo.pixelRatio : height,
                })
            }
            wx.showLoading({
                title: '正在初始化'
            })
            setTimeout(() => {
                wx.createSelectorQuery().in(this).select('#signature').fields({
                    node: true,
                    size: true
                }).exec(this.initCanvas.bind(this))
            }, 1000)
        },
        initCanvas(res) {
            const node = res.pop(),
                canvas = node.node,
                dpr = wx.getSystemInfoSync().pixelRatio;
            canvas.width = node.width * dpr;
            canvas.height = node.height * dpr;
            canvasContext = canvas.getContext('2d')
            canvasContext.scale(dpr, dpr)
            this.clearCanvas();
            wx.hideLoading();
        },
        clearCanvas() {
            const {penColor, textAlign, textBaseline, textFont, textObj, width, height} = this.data;
            canvasContext.clearRect(0, 0, width, height)
            /* canvasContext.font = textFont;
             canvasContext.fillStyle = penColor;
             canvasContext.textAlign = textAlign;
             canvasContext.textBaseline = textBaseline;
             canvasContext.fillText(textObj.content, textObj.x ?? width / 2, textObj.y ?? 30, textObj.maxWidth ?? width)*/
        },
        touchstart(e) {
            this.setData({
                isDrawing: true,
                lastX: e.touches[0].clientX,
                lastY: e.touches[0].clientY
            });
        },
        touchmove(e) {
            if (!this.data.isDrawing) return
            if (e.touches.length > 1) {
                return
            }
            const {penColor, penWidth, lastX, lastY} = this.data;
            canvasContext.strokeStyle = penColor;
            canvasContext.lineWidth = penWidth;
            canvasContext.beginPath();
            canvasContext.moveTo(lastX, lastY)
            canvasContext.lineTo(e.touches[0].clientX, e.touches[0].clientY)
            canvasContext.stroke()
            canvasContext.closePath()
            this.setData({
                lastX: e.touches[0].clientX,
                lastY: e.touches[0].clientY
            });
        },
        touchend(e) {
            this.setData({
                isDrawing: false
            });
        },
        async canvasToImage() {
            const query = wx.createSelectorQuery().in(this),
                that = this;
            const canvasObj = await new Promise((resolve, reject) => {
                query.select('#signature')
                    .fields({node: true, size: true})
                    .exec(async (res) => {
                        console.log(res[0])
                        wx.showLoading({
                            title: '正在导出',
                            icon: 'none'
                        });
                        setTimeout(() => {
                            wx.canvasToTempFilePath({
                                canvas: res[0].node,
                                success: res => {
                                    wx.hideLoading();
                                    this.triggerEvent("export", res.tempFilePath ?? false);
                                    if (that.data.saveToAlbum) {
                                        that.saveImageToPhotosAlbum(res.tempFilePath)
                                    }
                                }
                            })
                        }, 1000)
                    })
            });

        },
        saveImageToPhotosAlbum(imgUrl) {
            if (imgUrl) {
                wx.saveImageToPhotosAlbum({
                    filePath: imgUrl,
                    success: (res) => {
                        console.log(res)
                        wx.showToast({
                            title: '保存成功',
                            icon: 'success',
                            duration: 3000
                        })
                    },
                    fail: (err) => {
                        console.log(err)
                        wx.showToast({
                            title: '保存失败',
                            icon: 'error',
                            duration: 3000
                        })
                    }
                })
            } else {
                wx.showToast({
                    title: '绘制中……',
                    icon: 'loading',
                    duration: 3000
                })
            }
        }
    }
});
